package com.luhuiguo.cms.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Article;
import com.luhuiguo.cms.server.service.ArticleService;
import com.luhuiguo.cms.server.util.MapperUtils;
import com.luhuiguo.cms.shared.model.ArticleModel;
import com.luhuiguo.cms.shared.rpc.CreateDraftArticle;
import com.luhuiguo.cms.shared.rpc.CreateDraftArticleResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class CreateDraftArticleHandler implements ActionHandler<CreateDraftArticle, CreateDraftArticleResult> {

    @Autowired
    private ArticleService articleService;

    @Override
    @PreAuthorize("isAuthenticated()")
    public CreateDraftArticleResult execute(CreateDraftArticle action, ExecutionContext context) throws ActionException {

        Article article = new Article();
        article.setTitle("New Article");
        article.setChannelId(action.get());
        article.setStatus(ArticleModel.DRAFT);
        articleService.saveArticle(article);

        ArticleModel model = MapperUtils.map(article, ArticleModel.class);
        model.setStatus(ArticleModel.APPROVED);
        return new CreateDraftArticleResult(model);
    }

    @Override
    public Class<CreateDraftArticle> getActionType() {
        return CreateDraftArticle.class;
    }

    @Override
    public void rollback(CreateDraftArticle action, CreateDraftArticleResult result, ExecutionContext context)
            throws ActionException {

    }

}
